package com.example.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class BeanSqlHelper {
    private final static Logger logger = LoggerFactory.getLogger(Object.class);

    private static StringBuffer strBuf = new StringBuffer();

    public static Connection getConnection(){
        Connection connection = null;
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url="jdbc:mysql://localhost:3306/car_repair";
            String userName="root";
            String passWord ="MYSQL";
            connection = DriverManager.getConnection(url,userName,passWord);
            logger.info("数据库链接成功!");
        }catch(Exception ex){
            logger.error("数据库未连接!:"+ex);
        }
        return connection;
    }

    /**
     *直接生成insert语句
     * @param tableName:表名;
     * @return
     */
    public static StringBuffer insertSql(String tableName) {
        Connection conn = getConnection();
        String sql = "select * from "+tableName+"";
        PreparedStatement stmt;
        List<String> list = new ArrayList<>();
        strBuf.append("insert into "+tableName+" (");
        try{
            stmt = conn.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData data = rs.getMetaData();
                for(int j = 1; j <= data.getColumnCount(); j++){
                    if(j == data.getColumnCount()){
                        strBuf.append(data.getColumnName(j)+") ");
                        strBuf.append("values(");
                    }else{
                        strBuf.append(data.getColumnName(j)+",");
                    }
                    if(strBuf.toString().contains("values")){
                        for(int i = 1; i <= data.getColumnCount(); i++){
                            if(i==data.getColumnCount()){
                                strBuf.append("#{");
                                strBuf.append(data.getColumnName(i));
                                strBuf.append("})");
                            }else {
                                strBuf.append("#{");
                                strBuf.append(data.getColumnName(i));
                                strBuf.append("},");
                            }
                        }
                    }
                }
            System.out.println(strBuf);
        }catch(Exception ex){

        }
        return strBuf;
    }

    /**
     *直接生成update语句
     * @param tableName:表名
     * @return
     */
    public static StringBuffer updateSql(String tableName){

        Connection connection = getConnection();

        return null;
    }
    public static void main(String[] args) {

        StringBuffer str = BeanSqlHelper.insertSql("cr_sales_account");
    }
}
